
var netUtil = require('/../../utils/netUtil.js');
var util = require('/../../utils/util.js');
var app = getApp();

Page({

  data: {
    sendSmsCodeText: '发送验证码',
    sendSmsInteval: null,    //发送验证码倒计时的定时器
    idcardPositiveUrl: '../../images/sfzfm.png',   //身份证正面的url
    idcardOthersideUrl: '../../images/sfzzm.png',  //身份证反面的url
    isVerifyCodeTrue: false,  //验证码是否正确的标志位，默认不正确
    phoneNum: '',
    verifyCode: '',
    customerName: '',
    postCode: '',
    address: '',
    provinceCityRegion: ''   //用户选择的省市区
  },

  onLoad: function (options) {
    var that = this;

    app.getUserOpedId(function () {

      var params = {
        method: 'wechat.wisen.login.userInfo.queryUserIntfo',
        openId: app.globalData.userInfo.openid
      }

      netUtil.buildRequest(that, '/wisen/api/wechat/ret', params, {

        onPre: function () {
          netUtil.showLoadingDialog(that);
        },

        onSuccess: function (resp) {
          console.log(resp);

          netUtil.hideLoadingDialog(that);

          if (resp.ret == app.globalData.respSuccessCode) {

            var customer = resp.data;
            var phoneNum = customer.phoneNum;
           
            var customerName = customer.customerName;
           
            var address = customer.address;
            var idcardPositiveUrl = app.globalData.apiHeadUrl+customer.frontPhoto;
            var idcardOthersideUrl = app.globalData.apiHeadUrl+customer.reversePhoto;
            that.setData({
              
              phoneNum: phoneNum,
              
              customerName: customerName,
             
              address: address,
              idcardPositiveUrl: idcardPositiveUrl,
              idcardOthersideUrl: idcardOthersideUrl
            });

          } else {
            if (resp.message != undefined && resp.message != null && resp.message != '') {
              netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
            } else {
              netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
            }
          }

        },

        onError: function (res) {
          console.log("fail");
          netUtil.hideLoadingDialog(that);
          netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
        }

      }).send();

    });
  },

  onReady: function () {

  },

  onShow: function () {

    // 页面显示
  },

  onHide: function () {
    // 页面隐藏
  },

  onUnload: function () {
    // 页面关闭

  },

  inputPhone: function (e) {
    var phoneNum = e.detail.value;
    this.setData({
      phoneNum: phoneNum
    });
  },

  inputCustomerName: function (e) {
    var customerName = e.detail.value;
    this.setData({
      customerName: customerName
    });
  },

  inputPostCode: function (e) {
    var postCode = e.detail.value;
    this.setData({
      postCode: postCode
    });
  },

  inputAddress: function (e) {
    var address = e.detail.value;
    this.setData({
      address: address
    });
  },

  //点击发送验证码触发的方法
  sendSms: function () {

    var that = this;

    //如果已经发送过验证码，一分钟倒计时还没完成，不做处理
    if (that.data.sendSmsCodeText != '发送验证码') {
      var secStr = '';

      if (that.data.sendSmsCodeText.length == 6) {
        secStr = that.data.sendSmsCodeText.substring(0, 2);
      } else {
        secStr = that.data.sendSmsCodeText.substring(0, 1);
      }

      var secInt = parseInt(secStr);
      var newSecInt = secInt - 1;

      if (newSecInt <= 0) {

        this.setData({
          sendSmsCodeText: '发送验证码'
        });

        clearInterval(that.data.sendSmsInteval);

        that.setData({
          sendSmsInteval: null
        });

      } else {
        that.setData({
          sendSmsCodeText: newSecInt + '秒后重发'
        });
      }
      return;
    }

    var phoneNum = this.data.phoneNum;
    if (phoneNum != null && phoneNum.length == 11 && util.isPoneAvailable(phoneNum)) {

      app.getUserOpedId(function () {

        var params = {
          method: 'wechat.wisen.commom.verify.generate',
          openId: app.globalData.userInfo.openid,
          data: {
            phoneNum: that.data.phoneNum
          }
        };

        netUtil.buildRequest(that, '/wisen/api/wechat/ret', params, {

          onPre: function () {
            netUtil.showLoadingDialog(that);
          },

          onSuccess: function (resp) {

            netUtil.hideLoadingDialog(that);

            if (resp.ret == app.globalData.respSuccessCode) {

              if ('发送验证码' == that.data.sendSmsCodeText) {
                var text = '60秒后重发';
                that.setData({
                  sendSmsCodeText: text
                });

                var sendSmsInteval = setInterval(that.sendSms, 1000);

                that.setData({
                  sendSmsInteval: sendSmsInteval
                });

              }

            } else {
              if (resp.message != undefined && resp.message != null && resp.message != '') {
                netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
              } else {
                netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
              }
            }

          },

          onError: function (res) {
            console.log("fail");
            netUtil.hideLoadingDialog(that);
            netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
          }

        }).send();

      });

    } else {
      netUtil.showAlertDialog("提示", '请输入正确手机号码', false, "确定", null, null);
    }
  },

  //检查验证码是否正确
  checkSmsCode: function (e) {

    var that = this;

    var verifyCode = e.detail.value;

    //发送请求检查验证码
    if (verifyCode != null && verifyCode != '') {
      app.getUserOpedId(function () {
        var params = {
          method: 'wechat.wisen.commom.verify.check',
          openId: app.globalData.userInfo.openid,
          data: {
            phoneNum: that.data.phoneNum,
            verifyCode: verifyCode
          }
        };

        netUtil.buildRequest(that, '/wisen/api/wechat/ret', params, {
          onPre: function () {

          },

          onSuccess: function (resp) {

            //如果验证码正确，不做处理
            if (resp.ret == app.globalData.respSuccessCode) {
              that.setData({
                verifyCode: verifyCode,
                isVerifyCodeTrue: true
              });
            } else {   //验证码错误，弹出提示框
              netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
            }
          },

          onError: function (res) {
            console.log("fail");
            netUtil.hideLoadingDialog(that);
            netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
          }

        }).send();

      });
    }
  },

  submitRegister: function (e) {

    var that = this;

    if (this.data.phoneNum == null || this.data.phoneNum == '') {
      netUtil.showAlertDialog("提示", '请输入手机号码', false, "确定", null, null);
      return;
    }

    if (this.data.verifyCode == null || this.data.verifyCode == '') {
      netUtil.showAlertDialog("提示", '请输入验证码', false, "确定", null, null);
      return;
    }

    if (this.data.customerName == null || this.data.customerName == '') {
      netUtil.showAlertDialog("提示", '请输入用户名', false, "确定", null, null);
      return;
    }

    if (this.data.address == null || this.data.address == '') {
      netUtil.showAlertDialog("提示", '请输入地址', false, "确定", null, null);
      return;
    }

    if (!this.data.isVerifyCodeTrue) {
      netUtil.showAlertDialog("提示", '验证码错误', false, "确定", null, null);
      return;
    }

    if (this.data.idcardPositiveUrl == null || this.data.idcardPositiveUrl == '' || this.data.idcardPositiveUrl == '../../images/sfzfm.png') {
      netUtil.showAlertDialog("提示", '请选择身份证正面', false, "确定", null, null);
      return;
    }

    if (this.data.idcardOthersideUrl == null || this.data.idcardOthersideUrl == '' || this.data.idcardOthersideUrl == '../../images/sfzzm.png') {
      netUtil.showAlertDialog("提示", '请选择身份证反面', false, "确定", null, null);
      return;
    }

    app.getUserOpedId(function () {
      var params = {
        method: 'wechat.wisen.login.userInfo.update',
        openId: app.globalData.userInfo.openid,
        data: {
          phoneNum: that.data.phoneNum,
          customerName: that.data.customerName,
          postCode: that.data.postCode,
          address: that.data.provinceCityRegion + that.data.address,
          verifyCode: that.data.verifyCode,

        }
      };

      netUtil.buildRequest(that, '/wisen/api/wechat/ret', params, {

        onPre: function () {
          netUtil.showLoadingDialog(that);
        },

        onSuccess: function (resp) {

          //如果上传注册信息成功 ，就上传身份证 正面
          if (resp.ret == app.globalData.respSuccessCode) {

            var formData = {};

            formData.openId = app.globalData.userInfo.openid;
            formData.photo = 'A';

            wx.uploadFile({
              url: app.globalData.apiHeadUrl + '/wisen/wechat/upload/picture', //仅为示例，非真实的接口地址
              filePath: that.data.idcardPositiveUrl,
              name: 'file',
              formData: formData,
              success: function (res) {
                console.log(res);
                var resp = JSON.parse(res.data);

                if (resp.ret == app.globalData.respSuccessCode) {

                  var formData = {};

                  formData.openId = app.globalData.userInfo.openid;
                  formData.photo = 'B';

                  wx.uploadFile({
                    url: app.globalData.apiHeadUrl + '/wisen/wechat/upload/picture', //仅为示例，非真实的接口地址
                    filePath: that.data.idcardPositiveUrl,
                    name: 'file',
                    formData: formData,
                    success: function (res) {

                      console.log(res);

                      var resp = JSON.parse(res.data);

                      if (resp.ret == app.globalData.respSuccessCode) {

                        //注册并上传身份证成功后，跳转到首页
                        wx.reLaunch({
                          url: '/pages/index/index'
                        });

                      } else {
                        if (resp.message != undefined && resp.message != null && resp.message != '') {
                          netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
                        } else {
                          netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
                        }
                      }
                    }
                  });


                } else {
                  if (resp.message != undefined && resp.message != null && resp.message != '') {
                    netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
                  } else {
                    netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
                  }
                }
              }
            });

          } else {
            if (resp.message != undefined && resp.message != null && resp.message != '') {
              netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
            } else {
              netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
            }
          }

        },

        onError: function (res) {
          console.log("fail");
          netUtil.hideLoadingDialog(that);
          netUtil.showAlertDialog("提示", msgCanShow, false, "确定", null, null);
        },

        onEnd: function () {
          netUtil.hideLoadingDialog(that);
        }

      }).send();
    })

  },


  //选择身份证正面
  chooseIdcardPositive: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        if (tempFilePaths != null && tempFilePaths.length > 0) {
          console.log(tempFilePaths[0]);
          that.setData({
            idcardPositiveUrl: tempFilePaths[0]
          })
        }


        //下面是为了单独测试文件上传 的代码，调通后删掉

        /*						var formData = {};
                	
                    formData.openId = app.globalData.userInfo.openid;
                    formData.photo = 'A'	
        	
                     
                     var url = app.globalData.apiHeadUrl + '/cs/wisen/wechat/upload/picture';
                     console.log(url)
                     console.log(formData);
                            wx.uploadFile({
                              url: url, 
                            filePath: that.data.idcardPositiveUrl,
                            name: 'file',
                            formData:formData,
                            success: function(resp){
                            	
                              console.log(resp);
                            	
                              if(resp.ret == app.globalData.respSuccessCode) {
                              	
                                //注册并上传身份证成功后，跳转到首页
                                wx.reLaunch({
                                  url: '/pages/index/index'
                                });
                        	
                                } else {
                                if(resp.message != undefined && resp.message != null && resp.message != '') {
                                    netUtil.showAlertDialog("提示", resp.message, false, "确定", null, null);
                                  } else {
                                    netUtil.showAlertDialog("提示", "网络请求失败", false, "确定", null, null);
                                  }
                              }
                            }
                          });*/
      }
    })


  },

  //选择省份证反面
  chooseIdcardOthersize: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        if (tempFilePaths != null && tempFilePaths.length > 0) {
          console.log(tempFilePaths[0]);
          that.setData({
            idcardOthersideUrl: tempFilePaths[0]
          })
        }
      }
    })
  },

  backToIndex: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    });
  },

  provinceCityRegionChange: function (e) {
    var provinceCityRegion = e.detail.value;
    var province = provinceCityRegion[0];
    var city = provinceCityRegion[1];
    var region = provinceCityRegion[2];

    this.setData({
      provinceCityRegion: province + city + region
    });
  },
  


})